import  React from 'react';
import { Form, Input, Button, message } from 'antd';
import { UserOutlined, LockOutlined } from '@ant-design/icons';
import { connect } from 'react-redux'; //本意不是高阶组件
import { loginFn } from '../../api/user';


const Login = (props) => {
  const onFinish = (values) => {
    console.log('Received values of form: ', values);
    props.loginAction(values)
  };

  return (
    <div className="loginBox"> 
      <Form
        name="normal_login"
        className="login-form"
        initialValues={{
          remember: true,
        }}
        onFinish={onFinish}
      >
        <Form.Item
          name="adminname"
          rules={[
            {
              required: true,
              message: '请输入管理员账户！',
            },
          ]}
        >
          <Input prefix={<UserOutlined className="site-form-item-icon" />} placeholder="管理员账户" />
        </Form.Item>
        <Form.Item
          name="password"
          rules={[
            {
              required: true,
              message: '请输入密码!',
            },
          ]}
        >
          <Input
            prefix={<LockOutlined className="site-form-item-icon" />}
            type="password"
            placeholder="密码"
          />
        </Form.Item>

        <Form.Item>
          <Button type="primary" htmlType="submit" className="login-form-button">
            登录
          </Button>
        </Form.Item>
      </Form>
    </div>
  )
}
// 这次把异步操作在组件內使用
// connect(() => {}, () => {})
export default connect (
  () =>({}),
  (dispatch) => {
    return {
      loginAction (params) {
        loginFn(params).then(res => {
          console.log('1111', res);
          if (res.code === '10003') {
            message.error('密码错误')
          }  else if (res.code === '10005') {
            message.error('该管理员账户不存在')
          } else {
            message.success('登录成功')
            // 保留状态在本地
            localStorage.setItem('isLogin', true)
            localStorage.setItem('token', res.data.token)
            localStorage.setItem('adminname', res.data.adminname)
            localStorage.setItem('role', res.data.role )
            // 更新状态管理器
            dispatch({
              type: 'CHANGE_LOGIN_STATE',
              payload: 'true'
            })
            dispatch({ 
              type: 'CHANGE_TOKEN', 
              payload: res.data.token
            })
            dispatch({
              type: 'CHANGE_ADMINNAME_NAME',
              payload: res.data.adminname
            })
            dispatch({
              type: 'CHANGE_ROLE',
              payload: res.data.role
            })
            // 登录成功后跳转到首页
            window.location.href = '/'
          }
        })
      }
    }
  }
)(Login)